<template>
  <page-header-wrapper>
    <a-card>
      <p style="display:flex;justify-content:space-between">
        日期设置
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </p>
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :hideRequiredMark="true"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="初步协议签订日期：" prop="agreementDate">
              <a-date-picker v-model="form.agreementDate" :disabled-date="disabledDate" :disabled="Archive == 1" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同签订日期：" prop="contractDate">
              <a-date-picker v-model="form.contractDate" :disabled="Archive == 1" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <p style="display:flex;justify-content:space-between">
        文件：
        <a-upload :showUploadList="false" :customRequest="upload" accept=".doc,.docx,.pdf,.xlsx,.xls,image/*">
          <a-button :loading="uploading" type="primary">上传文件</a-button><br />
        </a-upload>
      </p>

      <span class="flex justify-end"> 支持扩展名：.doc、.docx、.pdf、.xlsx、.xls 、image/*</span><br />
      <a-table rowKey="id" :columns="columns" :data-source="data">
        <span slot="createTime" slot-scope="createTime"> {{ humanizeDate(createTime) }}</span>
        <template slot="operation" slot-scope="text, record">
          <a @click="download(record)">查看</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除吗?" @confirm="() => onDelete(record.id)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { getFile, creatFile, deleteFile, updateProjectById, getProjectById, getDetailList } from '@/api/common'
import moment from 'moment'
import OSSClient from '@/utils/oss'
const client = new OSSClient()
import { commonRule, dateRule } from '@/utils/rules'

const columns = [
  {
    title: '编号',
    dataIndex: 'ids',
    key: 'ids'
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
    key: 'fileName'
  },
  {
    title: '上传日期',
    dataIndex: 'createTime',
    key: 'createTime',
    scopedSlots: { customRender: 'createTime' }
  },
  {
    title: '文件类型',
    dataIndex: 'fileFormat',
    key: 'fileFormat'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  name: 'Operation',
  data() {
    return {
      columns,
      data: [],
      Archive: 0,
      labelCol: { span: 6 },
      wrapperCol: { span: 17 },
      applyDate: null,
      form: {
        agreementDate: null,
        contractDate: null
      },
      rules: {
        agreementDate: dateRule
        // contractDate: dateRule
      },
      uploading: false
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getData()
    this.getFileList()
  },
  methods: {
    disabledDate(endValue) {
      const startValue = this.applyDate
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    download(record) {
      let suffix = record.fileUrl.split('.').pop()
      if (['doc', 'docx', 'xls', 'xlsx'].includes(suffix)) {
        window.open(`https://view.officeapps.live.com/op/view.aspx?src=${window.encodeURIComponent(record.fileUrl)}`)
      } else {
        window.open(record.fileUrl)
      }
    },
    humanizeDate(v) {
      if (v) {
        return moment(v * 1000).format('YYYY-MM-DD') || '--'
      } else {
        return '-'
      }
    },
    async getData() {
      const id = this.$route.query.id
      const r = await getDetailList(id)
      this.Archive = r.result.data.Archive
      const res = await getProjectById(id)
      // console.log(res.result.data)
      var _form = res.result.data
      this.applyDate = _form.applyDate ? moment(_form.applyDate * 1000) : null
      let newData = {}
      for (let k in this.form) {
        newData[k] = _form[k]
      }
      newData.agreementDate = newData.agreementDate ? moment(newData.agreementDate * 1000) : null
      newData.contractDate = newData.contractDate ? moment(newData.contractDate * 1000) : null
      Object.assign(this.form, newData)
    },
    onSubmit() {
      var id = this.$route.query.id
      const form = Object.assign({}, this.form)
      form.agreementDate = Number(form.agreementDate.startOf('day').format('X'))
      form.contractDate = form.contractDate ? Number(form.contractDate.startOf('day').format('X')) : null
      this.$refs.form.validate(valid => {
        if (valid) {
          updateProjectById(id, form)
        }
      })
      this.$emit('update')
      this.$router.back(-1)
    },
    async getFileList() {
      let count = 0
      var id = this.$route.query.id
      const res = await getFile({
        projectId: id,
        relationType: 3
      })
      this.data = res?.result?.data || []
      this.data.forEach(el => {
        el.ids = ++count
      })
    },
    async onDelete(id) {
      await deleteFile(id)
      this.$message.info('已删除')
      this.getFileList()
    },
    async upload(obj) {
      try {
        this.uploading = true
        let url = await client.upload(obj.file, this.id, 3)
        await this.createFile(obj.file.name, url)

        this.uploading = false
        this.$message.success('上传成功')
        this.getFileList()
      } catch (err) {
        console.error(err)
        this.$message.error('上传失败')
      }
    },
    async createFile(filename, url) {
      let [name, suffix] = filename.split('.')
      const data = {
        fileName: name,
        fileFormat: suffix,
        projectId: this.id,
        relationType: 3,
        fileUrl: url
      }
      return await creatFile(data)
    }
  }
}
</script>
<style scoped>
.width {
  width: 150px;
}
</style>
